<?php
/**
 * 发货单
 * AUTHOR  : zlf
 * DateTime: 2022/07/27
 */
namespace App\Api\Controllers;

/* use App\Http\Controllers\Controller; */
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Api\Services\DispatchListService;
use Illuminate\Support\Facades\DB;
use App\Api\Models\DeliverGoodsModel;
use App\Http\Controllers\Api\BaseController;
use App\Helper\Utils\TimeUtil;
use App\Api\Services\MaterielTypeService;
use App\Api\Models\DispatchListModel;

class DispatchListController extends BaseController
{
    /**
     * 添加发货单
     */
    public function add(Request $request){           
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'consignee'         =>'string',//收货人
            'phone'             =>'string',//收货人联系电话
            'address'           =>'string',//收货地址         
            'deliver_time'      =>'string',//发货时间
            'deliver_person'    =>'string',//发货人          
            'total_number'      =>'integer',//商品总件数           
            'order_time'        =>'string',//下单时间 
            'total_cost'        =>'string',//总费用
            'total_cost_dx'     =>'string',//总费用大写
            'phone'             =>'regex:/^1[3456789][0-9]{9}$/',
            'total_cost'        =>'numeric|min:0',//总费用
            'total_number'      =>'numeric|min:0',//商品总件数
        ],[
            'total_cost.numeric'   => '本单费用只能为数字',         
            'total_cost.min'       => '本单费用最小只能为0',
            'total_number.numeric' => '商品件数只能为数字',
            'total_number.min'     => '商品件数最小只能为0',
            'phone.regex'          => '收货人手机号,格式错误!',

      ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        if(!empty($customer_signature_files = $request->file('customer_signature'))){

            if($customer_signature_files->isValid()){
                 
                $img_path = $customer_signature_files->store('qm/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['customer_signature'] = '/uploads/'.$img_path;
            }else{             
                return response()->json(['code' => 1,'msg' => '客户签字，添加失败！','data' => '']);
            }
             
        }
        //开启事务
        DB::beginTransaction();        
        try{
            //发货单
            $dData = $data;           
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();
            /* $dData['deliver_time'] = strtotime($data['deliver_time']);             */
            $dData['created_at']   = time();
            
            if(empty($dData['order_no'])){
                
                $dData['order_no']     = 'F'. $this->getMainUserId().TimeUtil::getMillisecond();//发货单号             
            }
            $dispatch_id           = DispatchListService::add($dData);
            //$data['goods_info']='[{"name":"葡萄","type_name":"紫","product_unit":"红富士","price":"5.6","num":"10","number_parcels":"5","serial_number":11},{"name":"水梨","type_name":"黄","product_unit":"砀山梨","price":"3.6","num":"8","number_parcels":"4","serial_number":22}]';
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){
                
                $goodsInfo = json_decode($data['goods_info'],true);
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as &$value){
                                            
                        $value['created_at']  = time();
                        $value['dispatch_id'] = $dispatch_id;
                        $value['user_id']     = $this->getUserId();
                        $value['main_id']     = $this->getMainUserId();
                    }
                    
                    DeliverGoodsModel::insert($goodsInfo);
                }
            }
           
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加发货单');
        }  
    }
    
    /**
     * 删除发货单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        
        $list = DispatchListModel::select('id')->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        
        if(!empty($list)){
                     
            foreach ($list as $k=>$v){
            
                $id_data[]=$v['id'];
            }
            
            $bool = DispatchListModel::where($condition)->whereIn('id',$id_data)->delete();
            
            if($bool){
            
                DeliverGoodsModel::where($condition)->whereIn('dispatch_id',$id_data)->delete();
            
                return $this->success();
                 
            }else{
                return $this->fail('','删除失败');
            }
        }
          return $this->fail('','发货单，不存在！');
    }
    
    /**
     * 修改发货单
     * 
     */
    public function update(Request $request){              
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'dispatch_id'       =>'required|integer',//发货单id
            'consignee'         =>'string',//收货人
            'phone'             =>'string',//收货人联系电话
            'address'           =>'string',//收货地址         
            'deliver_time'      =>'string',//发货时间
            'deliver_person'    =>'string',//发货人                     
            'total_number'      =>'integer',//商品总件数           
            'order_time'        =>'string',//下单时间 
            'total_cost'        =>'string',//总费用
            'total_cost_dx'     =>'string',//总费用大写               
            'phone'             =>'regex:/^1[3456789][0-9]{9}$/',
            'total_cost'        =>'numeric|min:0',//总费用
            'total_number'      =>'numeric|min:0',//商品总件数
        ],[
            'total_cost.numeric'   => '本单费用只能为数字',         
            'total_cost.min'       => '本单费用最小只能为0',
            'total_number.numeric' => '商品件数只能为数字',
            'total_number.min'     => '商品件数最小只能为0',
            'phone.regex'          => '收货人手机号,格式错误!',

      ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = DispatchListService::getDispatchListInfo(['id'=> $data['dispatch_id']]);
         
        if(empty($info)){
             
            return $this->fail('','发货单号,不存在！');
        }
        

        if(!empty($customer_signature_files = $request->file('customer_signature'))){
        
            if($customer_signature_files->isValid()){
                 
                $img_path = $customer_signature_files->store('qm/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['customer_signature'] = '/uploads/'.$img_path;
            }else{
                return response()->json(['code' => 1,'msg' => '客户签字，修改失败！','data' => '']);
            }             
        }
        //开启事务
        DB::beginTransaction();
        try{
            //发货单
            $updData = $data;                                
            if(isset($data['deliver_time'])) $updData['deliver_time'] = strtotime($data['deliver_time']);

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['dispatch_id'];
            //$updData['goods_info']='[{"goods_id":1,"name":"葡萄11","type_name":"紫11","product_unit":"件","price":"5.611","num":"1011","number_parcels":"5","serial_number":11},{"goods_id":2,"name":"水梨2222","type_name":"黄22","product_unit":"件","price":"3.6","num":"8","number_parcels":"4","serial_number":22},{"name":"水梨8888","type_name":"黄888","product_unit":"件","price":"3.6","num":"8","number_parcels":"4","serial_number":22}]';
            
            if(isset($updData['goods_info']) && !empty($updData['goods_info'])){
                
                $goodsInfo = json_decode($updData['goods_info'],true);
                
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as $value){//更新商品信息
                        //更新
                        if(isset($value['goods_id'])){
                            
                            $dCondition['id'] = $value['goods_id'];
                            
                            unset($value['goods_id']);
                            
                            DeliverGoodsModel::where($dCondition)->update($value);
                        }else{//添加
                            
                            $value['created_at'] = time();
                            $value['user_id']    = $this->getUserId();
                            $value['main_id']    = $this->getMainUserId();                       
                            $value['dispatch_id']= $updData['dispatch_id'];
                            
    
                            DeliverGoodsModel::insert($value);
                        }
                    }
                }
                unset($updData['goods_info']); unset($updData['dispatch_id']);
            }
            $updData['updated_at']   = time();
            $dispatch_id = DispatchListService::update($condition,$updData);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改发货单');
        }
  
    }

    /**
     * 发货单信息
     * @param dispatch_id
     */
    public function find(Request $request){          
        //参数验证
        $validator = Validator::make($data = $request->all(), [        
            'dispatch_id'       =>'required|integer',//发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        } 
        
        $condition['id']      = $data['dispatch_id'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        
        $info = DispatchListService::getDispatchListInfo($condition);
        $list = $info;
        if(!empty($info)){
            
            $list['goods_list']= DeliverGoodsModel::where(['dispatch_id'=>$info['id']])->get();
            
        }
        
       return $this->success($list);
    }
    
    /**
     * 发货单列表  
     */
    public function dispatchList(Request $request){
        
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $id_arr01 = [];
        $id_arr02 = [];
        $dispatch_id_arr = [];
        
        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        if(!empty($keyword)){
 
            $goodsList = DeliverGoodsModel::select('dispatch_id')
            ->where($condition)            
            ->where(function($query) use ($keyword) {   
                $query->orWhere('name', 'like', '%'.$keyword.'%');         
                $query->orWhere('type_name', 'like', '%'.$keyword.'%'); 
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('dispatch_id','DESC')
            ->get()->toArray(); 
            
            if(!empty($goodsList)){
                
                foreach ($goodsList as $k=>$v){
                    
                $id_arr01[$k] = $v['dispatch_id'];
                
                }
            }
          
            $list = DispatchListModel::select('id')->where($condition)
                ->where(function($query) use ($keyword) {
                    $query->orWhere('order_no', 'like', '%'.$keyword.'%');
                    $query->orWhere('consignee', 'like', '%'.$keyword.'%');
                    $query->orWhere('phone', 'like', '%'.$keyword.'%');
                    $query->orWhere('address', 'like', '%'.$keyword.'%');
                })->orderBy('id','desc')              
                ->get()->toArray();
                
                if(!empty($list)){
                
                    foreach ($list as $k=>$v){
                
                        $id_arr02[$k] = $v['id'];                
                    }
                }
                
                $dispatch_id_arr = array_unique(array_merge($id_arr01,$id_arr02));  
                
                if(empty($dispatch_id_arr)){
                
                    $dispatch_id_arr[0] ="0";
                }
        }

        $list = DispatchListService::getList($condition,$dispatch_id_arr,$data['page_size'],$data['current_page']);

        if(!empty($list['data'])){
            
            foreach ($list['data'] as &$value){
                
                $query = DeliverGoodsModel::where('dispatch_id',$value['id']);
                
                if(!empty($id_arr01)){
                    
                    $query->where(function($query) use ($keyword) {   
                    $query->orWhere('name', 'like', '%'.$keyword.'%');         
                    $query->orWhere('type_name', 'like', '%'.$keyword.'%');  
                    $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                    });               
                }
               $value['goods_info'] =  $query->get();
            }
        }
        return $this->success($list);
        
    }
    
    /**
     * 选择物料商品列表
     */
    public function selectGoods(Request $request){
        
        $keyword = empty($request->keyword)?'':$request->keyword;
        $condition = [];
        
        if(!empty($request->materiel_class_id)) {
            $condition['a.materiel_class_id'] = ['EQ' => $request->materiel_class_id];
        }
        
        return $this->success(
                MaterielTypeService::materielTypeSelect(
                $this->getMainUserId(),
                $keyword,
                $condition,
                $request->page_size,
                $request->current_page
                )
            );
    }
    
    /**
     * 创建编号
     */
    public function createNumber(Request $request){
        
        $number='F'. $this->getMainUserId().TimeUtil::getMillisecond();
        
        return $this->success(['number'=>$number]);
    }
}
